var table = new tree.ui.Table();
var toolbar = new tree.ui.HBox();
toolbar.set_style('width', 'auto');
toolbar.set_style('height', 'auto');

var proxy = new tree.io.rpc.JSON_Proxy('/rpc');

var timer = null;

var store = new tree.ui.Store({ Note: tree.ui.TYPES.string });

var lview = new tree.ui.Listview(store);

var button = new tree.ui.Button('Add new note');

button.connect('clicked', function(widget, evt)
{
    var name = prompt('Please enter Name:');
    store.append([name]);
    storage.save(name, '');
});

var area = new tree.ui.TextView();

var selected = '';

lview.connect('row-activated', function(widget, evt)
{
    var index = evt.index;
    var name = store.index(index)[0];
    selected = name;
    area.set_text(storage.get(name));
    upload();
});

toolbar.add(button);

var storage = new tree.persistence.Storage('notes');
storage.clear();

var server_notes = proxy.call_method('get_notes', []);

for(var key in server_notes)
{
    var value = server_notes[key];
    storage.save(key, value);
}

function upload()
{
    tree.ui.Statusbar.push('saving notes');
    var all_notes = storage.get_all();
    proxy.call_method('save_notes', [all_notes]);
    tree.ui.Statusbar.push('notes saved');
}

area.connect('changed', function(widget, evt)
{
    if(selected)
    {
        var text = widget.get_text();
        storage.save(selected, text);
        if(timer)
        {
            clearTimeout(timer);
        }
        timer = setTimeout(upload, 1000);
    }
});

var all_notes = storage.get_all();
for(var key in all_notes)
{
    var value = all_notes[key];
    store.append([key]);
}

table.add(button, 0, 0, '10%', '10%');
table.add(lview, 0, 1, '20%');
table.add(area, 1, 1);

document.body.appendChild(table.show());
